<?php
defined('SYSPATH') or die('No direct script access.');

class Controller_Messages extends Controller_Initialize {

  public $secure_actions = array(
      // user actions
      'index' => 'login',
      'view' => 'login',
      'sent' => 'login',
      'cache' => 'login',
      'delete' => 'login',
      'delete_cache' => 'login',
      'continue' => 'login',
      'read' => 'login',
      'tousername' => 'login',
  );

  public function before() {
    // Execute parent::before first
    parent::before();

  }

  public function action_index() {

    $view = View::factory('templates/messages/new');

    if (!empty($_POST)) {

      $messages_user = null;
      $messages_user = ORM::factory('messages_user');
      $post = $messages_user->validate_add_message($_POST);

      if ($post->check()) {
        $messages_user->to_username = $post['to_username'];
        $messages_user->username = $this->userAuth->username;
        $messages_user->text = $post['text'];
        $messages_user->date = time();
        $messages_user->save();
        if ($messages_user->saved()) {
          Message::add('success', 'Zpráva byla odeslána.');
          if (! ORM::factory('messages_cache')->where('username', '=', $this->userAuth->username)->where('pattern', '=', $_POST['pattern'])->delete_all()) {
            Message::add('warning', 'Rozepsaná zpráva nebyla smazána.');
          }
          Request::instance()->redirect('messages');
        }
      } else {
        $view->set('dataPost', $_POST);
        $informations = null;
        foreach($post->errors('messages_user') as $item) {
          $informations .= '<span>'.$item.'</span>';
        }
        Message::add('warning', '<strong>Zpráva nebyla odeslána.</strong> '.$informations);
      }
    }

    $this->template->content = $view;
    
  }

  public function action_view() {

    $this->template->content = View::factory('templates/messages/view')
                    ->bind('messages_user', $messages_user);

    $messages_user = ORM::factory('messages_user')->where('to_username', '=', $this->userAuth->username)->where('deleted_receiver', '=', null)->find_all();

  }

  public function action_read($id) {

    $this->template->content = View::factory('templates/messages/read')
      ->bind('messages_user', $messages_user);

    $messages_user = ORM::factory('messages_user')->where('to_username', '=', $this->userAuth->username)->find($id);
    $messages_user->read = 1;
    $messages_user->save();
  }

  public function action_sent() {

    $this->template->content = View::factory('templates/messages/sent')
                    ->bind('messages_user', $messages_user);

    $messages_user = ORM::factory('messages_user')->where('username', '=', $this->userAuth->username)->where('deleted', '=', null)->find_all();

  }

  public function action_cache($id = null) {

    if (!empty($_POST)) {
      $this->auto_render = FALSE;
      echo Kohana::debug($_POST);
      echo Kohana::debug($_POST['to_username']);
      echo Kohana::debug($_POST['text']);

      $model = null;
      $model = ORM::factory('messages_cache');
      $post = $model->validate_cache_message($_POST);

      if ($post->check()) {
        if (is_numeric($id)) {
        } else {
          $query = DB::query(Database::SELECT, "SELECT id, text FROM messages_cache WHERE username = '".$this->userAuth->username."' AND pattern = '".$_POST['pattern']."'")->execute()->current();

          if ($query) {
            $model_update = ORM::factory('messages_cache', $query['id']);
            $model_update->to_username = $_POST['to_username'];
            $model_update->text = $_POST['text'];
            $model_update->date = time();
            $model_update->save();

          } else {
            $model->username = $this->userAuth->username;
            $model->to_username = $_POST['to_username'];
            $model->text = $_POST['text'];
            $model->pattern = $_POST['pattern'];
            $model->date = time();
            $model->save();
          }
        }
      }
    }

    $this->template->content = View::factory('templates/messages/cache')
                    ->bind('messages_cache', $messages_cache);

    $messages_cache = ORM::factory('messages_cache')->where('username', '=', $this->userAuth->username)->find_all();

  }

  public function action_delete_cache($id) {

    ORM::factory('messages_cache')->where('username', '=', $this->userAuth->username)->delete($id);
    Request::instance()->redirect('messages/cache');

  }

  public function action_delete($where, $id) {
    
    if ($where === 'sent') {
      $model = ORM::factory('messages_user')->where('username', '=', $this->userAuth->username)->find($id);
      $model->deleted = 1;
      $model->save();
    } elseif ($where === 'view') {
      $model = ORM::factory('messages_user')->where('to_username', '=', $this->userAuth->username)->find($id);
      $model->deleted_receiver = 1;
      $model->save();
    }
    Request::instance()->redirect('messages/'.$where);

  }

  public function action_continue($id) {

    if (!empty($_POST)) {

      $messages_user = null;
      $messages_user = ORM::factory('messages_user');
      $post = $messages_user->validate_add_message($_POST);

      if ($post->check()) {
        echo Kohana::debug($post);
        $messages_user->to_username = $post['to_username'];
        $messages_user->username = $this->userAuth->username;
        $messages_user->text = $post['text'];
        $messages_user->date = time();
        $messages_user->save();
        if ($messages_user->saved()) {
          Message::add('success', 'Zpráva byla odeslána.');          
          if (! ORM::factory('messages_cache')->where('username', '=', $this->userAuth->username)->delete($id)) {
            Message::add('warning', 'Rozepsaná zpráva nebyla smazána.');
          }
          Request::instance()->redirect('messages');
        }
      } else {
        $view->set('dataPost', $_POST);
        $informations = null;
        foreach($post->errors('comments') as $item) {
          $informations .= '<span>'.$item.'</span>';
        }
        Message::add('warning', '<strong>Zpráva nebyla odeslána.</strong> '.$informations);
      }
    }

    $this->template->content = View::factory('templates/messages/continue')
      ->bind('messages_cache', $messages_cache);

    $messages_cache = ORM::factory('messages_cache')->where('username', '=', $this->userAuth->username)->find($id);
  }

  public function action_tousername() {

    $this->auto_render = FALSE;

    $q = strtolower($_GET["term"]);
    if (!$q) return;
    $query = DB::query(Database::SELECT, "SELECT username FROM users WHERE username LIKE '".$q."%'")->execute();

    $array = array();
    foreach ($query as $item) {
      $array[] = $item['username'];

    }

    echo json_encode($array);

  }

}